from flask import Blueprint,render_template,session,request,redirect,url_for,jsonify
from database import User#,EmailCaptcha
from exts import db
#from form import LoginForm,RegisterForm
from string import ascii_letters,digits
from datetime import datetime
from random import choices
from werkzeug.security import generate_password_hash,check_password_hash#加密

bp=Blueprint("auth",__name__,url_prefix='/auth')#前缀/ocean/auth

string=ascii_letters+str(digits)

# @bp.route('/',methods=['GET','POST'])
# def auth():
#     return render_template('login.html')

@bp.route('/login',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        account = request.json.get("account")
        password = request.json.get("account")

        # form=LoginForm(request.form)
        # if form.validate():
        #     account=form.account.data
        #     password=form.password.data

        user=User.query.filter_by(account=account).first()
        if not user:
            print('账号在数据库中不存在！')
            return jsonify({'code':400})#redirect(url_for('auth.login'))
        if user.password==password:#check_password_hash(user.password,password)
            #cookie只适合存储少量数据
            #flask的session是通过加密后存储在cookie中的
            session['user_id']=user.id
            return jsonify({'code':200})#redirect('/')
        else:
            print('账号和密码不匹配！')
            return jsonify({'code':400})#redirect('/auth/login')

        # else:
        #     print(form.errors)
        #     return redirect('/auth/login')

@bp.route('/register',methods=['GET','POST'])
def register():
    if request.method=='GET':
        return render_template('register.html')
    else:
        account = request.json.get("account")
        password = request.json.get("password")
        # 表单验证
        #form = RegisterForm(request.form)
        #if form.validate():  # 自动调用自定义函数
            #account = form.account.data
            #username = form.username.data
            #password = form.password.data

        user = User.query.filter_by(accoun=account).first()
        if user:
            print('该账号已存在')
            return jsonify({'code': 400})

        user = User(account=account, password=password)#email=email, username=username,generate_password_hash(password)
        db.session.add(user)
        db.session.commit()

        return jsonify({'code':200})#redirect(url_for('auth.login'))



@bp.route('/generate_account')
def generate_account():
    t=str(datetime.now()).split('.')[0].replace(' ','').replace(':','').replace('-','')
    accounts = User.query.filter(User.account.contains('1')).order_by(User.joint_time.desc()).with_entities(User.account).all()
    #print('accounts=',accounts)
    if accounts!=[]:
        flag=False
        while not flag:
            account = ''.join(choices(string, k=6))+t#14+6
            print(account)
            #print(len(account))
            if account not in accounts:
                flag=True

    return ''.join(choices(string, k=6))+t


@bp.route('/logout')
def logout():
    session.clear()
    return redirect('/')


